package com.nx.platform.entry.config;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * Created by nx on 2019/3/13.
 */
@Aspect
@Component
public class DynamicConfig {
    // @Value("${apollo.config.percentage}")
    private int errorThresholdPercentage = 1;
    
    @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
    public void pointcut() {
    }
    
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Around("pointcut()")
    public Object around(final ProceedingJoinPoint joinPoint)
        throws Throwable {
        Signature s = joinPoint.getSignature();
        MethodSignature ms = (MethodSignature)s;
        Method method = ms.getMethod();
        HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
        HystrixProperty[] hystrixProperties = hystrixCommand.commandProperties();
        for (HystrixProperty hystrixProperty : hystrixProperties) {
            if ("circuitBreaker.errorThresholdPercentage".equals(hystrixProperty.name())) {
                InvocationHandler h = Proxy.getInvocationHandler(hystrixProperty);
                Field hField = h.getClass().getDeclaredField("memberValues");
                hField.setAccessible(true);
                Map memberValues = (Map)hField.get(h);
                memberValues.put("value", errorThresholdPercentage);
            }
        }
        Object obj = joinPoint.proceed();
        return obj;
    }
}